import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/config/address.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

import '../../../hj_model/splash/domain_source_model.dart';

enum ChangeLineEntry {
  video,
  shortVideo;
}

extension _ on ChangeLineEntry {
  Widget instanceChangeLineView(String? line) {
    if (this == ChangeLineEntry.video) {
      return Row(children: [
        Text(
          line ?? '切换路线',
          style: TextStyle(color: Color(0xff999999), fontSize: 14),
        ),
        6.sizeBoxW,
        Image.asset(
          'change_line.png'.videoPath,
          width: 20.w,
          height: 20.w,
        )
      ]);
    }
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          "line_white.png".videoPath,
          width: 30,
          height: 30,
        ),
        Text(
          "路线",
          style: TextStyle(
            color: Color(0xffCCCCCC),
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }
}

class ChangeLineButton extends StatefulWidget {
  final ChangeLineEntry entry;
  final Function(String line) changeLineCallback;

  const ChangeLineButton(this.entry, {super.key, required this.changeLineCallback});

  @override
  State<ChangeLineButton> createState() => _ChangeLineButtonState();
}

class _ChangeLineButtonState extends State<ChangeLineButton> {
  final _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    Domain? selectedCnd = Address.cdnAddressLists.firstWhere((element) => element.url == Address.cdnAddress);
    return GestureDetector(
      key: _key,
      onTap: () async {
        final rb = _key.currentContext?.findRenderObject() as RenderBox?;
        if (rb == null) return;
        final size = rb.size;
        final offset = rb.localToGlobal(Offset.zero);
        final result = await Get.dialog(
            ChangeLineDialog(
              offset,
              targetSize: size,
              entry: widget.entry,
            ),
            useSafeArea: false,
            barrierColor: Colors.transparent);
        if (result != null) {
          widget.changeLineCallback.call(result!);
          setState(() {});
        }
      },
      child: widget.entry.instanceChangeLineView(selectedCnd.desc),
    );
  }
}

class ChangeLineDialog extends StatefulWidget {
  final Offset targetOffset;
  final Size targetSize;
  final ChangeLineEntry entry;
  const ChangeLineDialog(this.targetOffset, {super.key, required this.targetSize, this.entry = ChangeLineEntry.video});

  @override
  State<ChangeLineDialog> createState() => _ChangeLineDialogState();
}

class _ChangeLineDialogState extends State<ChangeLineDialog> {
  final width = 114.0;
  final margin = 18.w;
  late double dx;
  late double dy;
  late double height = Address.cdnAddressLists.length * 33;

  @override
  void initState() {
    super.initState();
    final dfx = widget.targetOffset.dx + width - Get.width;
    if (dfx >= 0) {
      dx = Get.width - width - 10;
    } else {
      dx = widget.targetOffset.dx;
    }
    final dfy = widget.targetOffset.dy + widget.targetSize.height + height - Get.height;
    if (dfy > 0) {
      dy = widget.targetOffset.dy - height - 10;
    } else {
      dy = widget.targetOffset.dy + widget.targetSize.height + 10;
    }
    if (widget.entry == ChangeLineEntry.shortVideo) {
      dx = dx - widget.targetSize.width - 10;
      dy = dy - height - 12;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          left: dx,
          top: dy,
          child: Container(
            width: 114,
            height: height,
            padding: EdgeInsets.only(left: 9, right: 9),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10),
                  topRight: Radius.circular(widget.entry == ChangeLineEntry.shortVideo ? 10 : 0),
                  bottomLeft: Radius.circular(10),
                  bottomRight: Radius.circular(widget.entry == ChangeLineEntry.shortVideo ? 0 : 10),
                ),
                color: Color(0xff16152A)),
            child: Material(
                color: Colors.transparent,
                child: MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: ListView.separated(
                    shrinkWrap: true,
                    itemCount: Address.cdnAddressLists.length,
                    separatorBuilder: (BuildContext context, int index) {
                      return Divider(
                        height: 1,
                        color: Color(0xff333333),
                      );
                    },
                    itemBuilder: (BuildContext context, int index) {
                      bool isSelected = Address.cdnAddressLists[index].url == Address.cdnAddress;
                      return GestureDetector(
                        onTap: () {
                          Get.back(result: Address.cdnAddressLists[index].url);
                        },
                        child: Container(
                          width: double.infinity,
                          alignment: Alignment.center,
                          height: 33,
                          child: Text(
                            Address.cdnAddressLists[index].desc ?? '',
                            style: TextStyle(color: isSelected ? Colors.blue : Color(0xffdbdbdb), fontSize: 14.sp),
                          ),
                        ),
                      );
                    },
                  ),
                )),
          ),
        )
      ],
    );
  }
}
